package com.example.mobileshop.utils;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;

public class CustomJSonArrayRequest<T> extends Request<T>{
	
	/** JSON parsing engine */
    protected final Gson gson;

    /** class of type of response */
    protected final Class<T> clazz;
	
	/** result listener */
    private final Listener<T> listener;
    
    /** output */
    private T output;
    
	public CustomJSonArrayRequest(String url, Class<T> clazz, Listener<T> listener, 
            ErrorListener errorListener) {
        super(Method.GET, url, errorListener);
        this.clazz = clazz;
        this.listener = listener;
        this.gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").create();        
	}
	
	@Override
	protected void deliverResponse(T response) {
		listener.onResponse(response);		
	}

	@Override
	protected Response<T> parseNetworkResponse(NetworkResponse response) {
	 try {
            String json = new String(
                    response.data, HttpHeaderParser.parseCharset(response.headers));
            this.output = gson.fromJson(json, clazz);
            return Response.success(
                    this.output, HttpHeaderParser.parseCacheHeaders(response));

        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JsonSyntaxException e) {
            return Response.error(new ParseError(e));
        }
	}



	public T getOutput() {
		return output;
	}



	public void setOutput(T output) {
		this.output = output;
	}
	
}